package com.github.postsanf.yinian.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.pop.PopTopayZidingyi;
import com.github.postsanf.yinian.bean.YNResponse;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNGetUserResponse;
import com.github.postsanf.yinian.utils.BigDecimalUtil;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.UIHelper;
import com.google.gson.Gson;
import com.litesuits.http.HttpConfig;
import com.litesuits.http.LiteHttp;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedHashMap;

import cn.beecloud.BCPay;
import cn.beecloud.async.BCCallback;
import cn.beecloud.async.BCResult;
import cn.beecloud.entity.BCPayResult;

public class MyWalletDialogActivity extends Activity implements View.OnClickListener {
    private RelativeLayout rl_mywallet;
    private TextView tv_mymoney;
    private RelativeLayout dialog_mywallet;
    private BaseApplication application;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_dialog_mywallet);
        application = (BaseApplication) getApplication();
        registerBoradcastReceiver();
        initView();
        getUserWallet();
    }

    private void getUserWallet() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynShowUserHead))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNGetUserResponse resUser = new Gson().fromJson(s, YNGetUserResponse.class);
                        if (resUser != null && ReqUtils.isSuccess(resUser.getCode()) && resUser.getData().size() > 0) {
                            String uBalance = resUser.getData().get(0).getuBalance();
                            if (!StringUtils.isEmpty(uBalance)) {
                                tv_mymoney.setText(uBalance);
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        LiteHttp.newApacheHttpClient(new HttpConfig(this)).executeAsync(req);
    }

    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionCloseactivity);
        myIntentFilter.addAction("updateMyWallet");
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionCloseactivity:
                    finish();
                    break;
                case "updateMyWallet":
                    getUserWallet();
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
    }


    private void initView() {
        findViewById(R.id.mywallet_close).setOnClickListener(this);
        dialog_mywallet = (RelativeLayout) findViewById(R.id.dialog_mywallet);
        dialog_mywallet.setOnClickListener(this);
        rl_mywallet = (RelativeLayout) findViewById(R.id.rl_mywallet);
        rl_mywallet.setOnClickListener(this);
        tv_mymoney = (TextView) findViewById(R.id.tv_mymoney);
        Animation translateAnimationf = new TranslateAnimation(0, 0, -UIHelper.dip2px(MyWalletDialogActivity.this, 220), 0);
        translateAnimationf.setDuration(500);
        rl_mywallet.startAnimation(translateAnimationf);
        findViewById(R.id.mywallet_pay).setOnClickListener(this);
        findViewById(R.id.mywallet_getcash).setOnClickListener(this);
        findViewById(R.id.tv_pay_history).setOnClickListener(this);
    }

    @Override
    public void onBackPressed() {

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.mywallet_close:
            case R.id.dialog_mywallet:
                dialog_mywallet.setClickable(false);
                Animation translateAnimationf = new TranslateAnimation(0, 0, 0, UIHelper.dip2px(MyWalletDialogActivity.this, 600));
                translateAnimationf.setDuration(600);
                rl_mywallet.startAnimation(translateAnimationf);
                translateAnimationf.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        rl_mywallet.setVisibility(View.GONE);
                        finish();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                });
                break;
            case R.id.rl_mywallet:
                break;
            case R.id.mywallet_pay:
                mpopTopay = new PopTopayZidingyi(this, ponClickListener);
                mpopTopay.showAtLocation(dialog_mywallet, Gravity.BOTTOM, 0, 0);
//                startActivity(new Intent(this, MyWalletChongZhiDialogActivity.class));
                break;
            case R.id.mywallet_getcash:
//                Toast.makeText(MyWalletDialogActivity.this, "提示 ：8月30日统一开放提现功能", Toast.LENGTH_LONG).show();
                startActivity(new Intent(this, MyWalletgetCashDialogActivity.class));
                break;
            case R.id.tv_pay_history:
                startActivity(new Intent(this, TransactionDetailsActivity.class));
                break;
        }
    }

    private PopTopayZidingyi mpopTopay;
    View.OnClickListener ponClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.to_pay_cash:
                    if (StringUtils.isEmpty(mpopTopay.price)) {
                        Toast.makeText(MyWalletDialogActivity.this, "充值为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    DownOrder(mpopTopay.price);
                    break;
            }
        }
    };

    String orderNumber;

    public void DownOrder(final String topayPrice) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put("userid", String.valueOf(application.getCurID()));
        mParam.put("money", topayPrice);
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/user/PlaceOrder")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        Log.i("xjs", "zsss==>" + s.toString());
                        try {
                            JSONObject resultOrder = new JSONObject(s.toString());
                            if (ReqUtils.isSuccess(resultOrder.optString("code"))) {
                                String transactionID = resultOrder.optJSONArray("data").optJSONObject(0).optString("transactionID");
                                orderNumber = resultOrder.optJSONArray("data").optJSONObject(0).optString("orderNumber");
                                HashMap<String, String> mapOptional = new HashMap<>();
                                mapOptional.put("userid", String.valueOf(application.getCurID()));
                                mapOptional.put("transactionID", transactionID);
                                mapOptional.put("orderNumber", orderNumber);
                                Log.i("xjs", "totalPrice==>" + topayPrice);
                                int zongPrice = BigDecimalUtil.multotal(topayPrice, "100");
                                Log.i("xjs", "zongPrice==>" + zongPrice);
                                Log.i("xjs", "orderNumber==>" + orderNumber);
                                if (zongPrice <= 0) {
                                    Toast.makeText(MyWalletDialogActivity.this, "有误，处理中！", Toast.LENGTH_SHORT).show();
                                    return;
                                }
                                BCPay.getInstance(MyWalletDialogActivity.this).reqAliPaymentAsync("武汉市追忆那年网络科技有限公司", zongPrice,
                                        orderNumber, mapOptional, callback);
                            } else {
                                Toast.makeText(MyWalletDialogActivity.this, "异常！", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        LiteHttp.newApacheHttpClient(new HttpConfig(this)).executeAsync(req);
    }

    private String toastMsg;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Toast.makeText(MyWalletDialogActivity.this, toastMsg, Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    TopUp();
                    Toast.makeText(MyWalletDialogActivity.this, toastMsg, Toast.LENGTH_SHORT).show();
                    finish();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    public void TopUp() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put("money", mpopTopay.price);
        mParam.put("orderNumber", orderNumber);
        StringRequest req = new StringRequest("https://api.zhuiyinanian.com/YinianProject/user/TopUp")
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNResponse resUser = new Gson().fromJson(s, YNResponse.class);
                        Log.i("xjs", "TopUp===>" + s);
                        if (resUser != null && resUser.getCode() == 0) {
                            finish();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        LiteHttp.newApacheHttpClient(new HttpConfig(this)).executeAsync(req);
    }

    BCCallback callback = new BCCallback() {
        @Override
        public void done(BCResult bcResult) {
            final BCPayResult bcPayResult = (BCPayResult) bcResult;
            String result = bcPayResult.getResult();
            Log.d("yuhao", "result=" + "支付失败, 原因: " + bcPayResult.getErrCode() +
                    " # " + bcPayResult.getErrMsg() +
                    " # " + bcPayResult.getDetailInfo());
            if (result.equals(BCPayResult.RESULT_SUCCESS)) {
                toastMsg = "用户支付成功";
                handler.sendEmptyMessage(2);
            } else if (result.equals(BCPayResult.RESULT_CANCEL)) {
                toastMsg = "用户取消支付";
                handler.sendEmptyMessage(1);
            } else if (result.equals(BCPayResult.RESULT_FAIL)) {
                toastMsg = "支付失败, 原因: " + bcPayResult.getErrCode() +
                        " # " + bcPayResult.getErrMsg() +
                        " # " + bcPayResult.getDetailInfo();
                handler.sendEmptyMessage(1);
            }

            if (bcPayResult.getId() != null) {
                //你可以把这个id存到你的订单中，下次直接通过这个id查询订单
                Log.w("xjs", "bill id retrieved : " + bcPayResult.getId());
                //根据ID查询，此处只是演示如何通过id查询订单，并非支付必要部分
                // getBillInfoByID(bcPayResult.getId());
            }
        }
    };

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }

}
